package com.jz.yanshe.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.response.BaseResponse;
import com.jz.jd.rest.response.VIPDetailResponse;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import com.jz.yanshe.util.PreferencesHelper;
import com.jz.yanshe.util.ZxingUtils;
import com.jz.yanshe.base.BaseActivity;
import com.jz.yanshe.R;
/**
 * Created by Administrator on 2018/3/16.
 */

public class InviteActivity extends BaseActivity{

    VIPDetailResponse.vipDetail vipDetail;
    @BindView(R.id.tv_invite_code)
    TextView tv_invite_code;
    @BindView(R.id.img_qr)
    ImageView img_qr;
    @BindView(R.id.parent_container)
    LinearLayout parent_container;
    private Handler mHandler = new Handler();
    @Override
    protected void initViews() {

}

    @Override
    protected void initData() {
        ViewTreeObserver vtb1 = img_qr.getViewTreeObserver();
        vtb1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                img_qr.getViewTreeObserver().addOnGlobalLayoutListener(this);
                LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) img_qr.getLayoutParams(); //取控件textView当前的布局参数 linearParams.height = 20;// 控件的高强制设成20
                linearParams.height = img_qr.getWidth();// 控件的宽强制设成30
                img_qr.setLayoutParams(linearParams); //使设置好的布局参数应用到控件


            }
        });
        vipDetail = (VIPDetailResponse.vipDetail) getIntent().getSerializableExtra("obj");
        tv_invite_code.setText(vipDetail.invite_code);
        parent_container.setDrawingCacheEnabled(true);
        parent_container.buildDrawingCache();
        getHTML();


    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_invite;
    }

    @OnClick(R.id.btn_download)
    void btn_download(){
        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // 要在运行在子线程中
                final Bitmap bmp = parent_container.getDrawingCache(); // 获取图片
                savePicture(bmp, System.currentTimeMillis()+".jpg");// 保存图片
                parent_container.destroyDrawingCache(); // 保存过后释放资源
            }
        },100);
    }

    public void savePicture(Bitmap bm, String fileName) {
        verifyStoragePermissions(this);

        Log.i("xing", "savePicture: ------------------------");
        if (null == bm) {
            Log.i("xing", "savePicture: ------------------图片为空------");
            return;
        }
        File foder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test");
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, fileName);
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            //压缩保存到本地
            bm.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "权限不足!", Toast.LENGTH_SHORT).show();
            return;
        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myCaptureFile)));
        Toast.makeText(this, "保存成功!", Toast.LENGTH_SHORT).show();
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    public  void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }


    private void getHTML(){
        RestProxy.getInstance().getHTML(PreferencesHelper.getInstance().getString(this, "token"), new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                Bitmap bitmap=ZxingUtils.createBitmap(baseResponse.url);
                Drawable drawable=new BitmapDrawable(bitmap);
                img_qr.setBackground(drawable);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

}
